const db = wx.cloud.database();
const dbUser = db.collection("user");

Page({
  // 注册
  reg(e) {
    let user = e.detail.value;
    console.log('user', user);
    if (!user.phone) {
      wx.showToast({
        icon: 'error',
        title: '请填写手机',
      });
    } else if (!user.password) {
      wx.showToast({
        icon: 'error',
        title: '请填写密码',
      });
    } else if (!user.name) {
      wx.showToast({
        icon: 'error',
        title: '请填写姓名',
      });
    } else {
      wx.request({
        url: 'http://localhost:8080/api/user/getPhone',
        method: 'GET',
        data: {
          phone: user.phone
        },
        success: (res) => {
          if (res.data.code === 200) {
            this.addUser(user);
            wx.switchTab({
              url: '/pages/login/login',
          })
          } else {
            wx.showToast({
              icon: 'error',
              title: '手机号已注册过',
              duration: 1500
            });
          }
        },
        fail: (error) => {
          console.error(error);
        }
      });
    }
  },

  // 添加用户
  addUser(user) {
    user._id = user.phone;
    // 给用户一个默认头像
    user.avatarUrl = '/image/no_login.png';
    wx.request({
      url: 'http://localhost:8080/api/user/register',
      method: 'POST',
      data: user,
      success: (res) => {
        if (res.data.code === 400) {
          wx.showToast({
            icon: 'error',
            title: res.data.data,
            duration: 1500
          });
        } else {
          wx.showToast({
            title: '注册成功！',
            icon: 'success',
            duration: 2500
          });
          setTimeout(() => {
            wx.navigateTo({
              url: '/pages/login/login',
            });
          }, 1000);
        }
      }
    });
  }
});
